package uk.ac.ok.cs.diadem.oxpath.worker;
import java.io.IOException;

import org.apache.commons.configuration.XMLConfiguration;
import org.gearman.Gearman;
import org.gearman.GearmanFunction;
import org.gearman.GearmanServer;
import org.gearman.GearmanWorker;


public class SingleWorker {

	private Gearman gearman;
	private String host, functionName,functionClassName;
	private int port,maxConcurrentJobs;
	
	//FIXME 
	//private XMLConfiguration configuration;

	public SingleWorker(String host, int port, String functionName, String functionClassName,int maxConcurrentJobs) {

		this.host = host;
		this.functionName=functionName;
		this.functionClassName = functionClassName;
		this.port=port;
		this.maxConcurrentJobs=maxConcurrentJobs;
	
	}
	
	public void createWorker()
	{
	Class tmpClass;
		
		try {
			tmpClass = Class.forName(functionClassName);


			GearmanFunction function = (GearmanFunction) tmpClass.newInstance();

			if (host==null || functionName==null || function==null)
				throw new IllegalArgumentException("parameters null");

			// Create a new gearman system
			this.gearman = Gearman.createGearman();


			// Create a GearmanWorker
			final GearmanWorker worker = gearman.createGearmanWorker();
			
			worker.setMaximumConcurrency(maxConcurrentJobs);

			// Register function
			worker.addFunction(functionName, function);

			/*
			 * Create the job server object. This call creates an object representing
			 * a remote job server.
			 *
			 * Parameter 1: the host address of the job server.
			 * Parameter 2: the port number the job server is listening on.
			 *
			 * A job server receives jobs from clients and distributes them to
			 * registered workers.
			 */
			GearmanServer server = gearman.createGearmanServer(host, port);


			// Adds a job server, may throw IOException
			worker.addServer(server);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}

	}

}
